import router from '@/router'
import type { ResponseData } from '@/type/ResponseData'
import axios, { type AxiosResponse } from 'axios'
import { ElMessage } from 'element-plus'
const http = axios.create({
  baseURL: 'api/',
  timeout: 15000,
})

http.interceptors.request.use((config) => {
  const token = localStorage.getItem('token')
  if (token && config.headers) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

http.interceptors.response.use(
  (response: AxiosResponse) => response, // 直接返回ResponseData
  (error: any) => {
    let msg = ''

    if (!error.response.data)
      msg = error.response.message;
    else {
      const responsedata = error.response.data
      const r = responsedata as any as ResponseData<string>
      msg = r.Message!;
    }
    ElMessage.error(msg)
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      router.push({
        path: '/login',
        query: {
          redirect: router.currentRoute.value.path // 使用当前路由路径
        }
      })
    }
    else return Promise.reject(msg)
  }
)

const post = <T>(url: string, arg?: any) => {
  return new Promise<ResponseData<T>>((resolve, rejects) => {
    http.post(url, arg).then((response) => {
      if (response.status === 200) {
        resolve(response.data as ResponseData<T>);
      }
    })
      .catch((err) => {
        rejects(err);
      });
  });
};
const get = <T>(url: string, arg?: any) => {
  return new Promise<ResponseData<T>>((resolve, rejects) => {
    http.get(url, { params: arg }).then((response) => {
      if (response.status === 200) {
        resolve(response.data as ResponseData<T>);
      }
    })
      .catch((err) => {
        rejects(err);
      });
  });
};
export { post, get };
